<template>
	<view>


		<titlebar :back="true" :text="text" :backgroundColor='backgroundColor' :color='color'
			:isIPhoneBangs="isIPhoneBangs" ref="isIPhoneBangs" />


		<view class="uni-margin-wrap">
			<swiper class="swiper" style="height: 414px;" circular :indicator-dots="true"
				indicator-color="rgba(0, 0, 0, .5)" indicator-active-color="#EA5404" :autoplay="true">
				<swiper-item class="swiper-item" v-for="item, inde in swiperList" :key="inde">
					<view class="item uni-bg-red">
						<image mode="widthFix" :src="item.image||'@appstatic/car/car_banner.jpg'">
						</image>
					</view>
				</swiper-item>
				<!-- <swiper-item class="swiper-item">
					<view class="item uni-bg-red">
						<image mode="widthFix" src="https://pfmotortest.hb4oss.xstore.ctyun.cn/2022-06-07/1481_e6e574bb-aade-42ad-a7f9-971d32700da1.png" ></image>
					</view>
				</swiper-item> -->
			</swiper>
		</view>
		<view class="example">
			<uni-forms ref="valiForm" :modelValue="valiFormData" label-position="top">
				<uni-forms-item label="预约车型" name="testModel">
					<!-- <uni-data-select v-model="valiFormData.name" :localdata="range" @change="change" placeholder="请选择预约车型"></uni-data-select> -->
					<picker @change="bindPickerChange" :value="testModelIndex" :range="range" range-key="modelName">
						<view class="uni-input">{{valiFormData.testModel ? valiFormData.testModel: '请选择预约车型'}}</view>
					</picker>
					<image class="arrow" src="@appstatic/message/message_icon_arrow.png"></image>
				</uni-forms-item>
				<uni-forms-item label="试驾城市" name="testCity">
					<!-- <uni-data-select v-model="valiFormData.city" :localdata="range" @change="change" placeholder="请选择试驾城市"></uni-data-select> -->
					<!-- <picker @change="bindPickerChange" data-type='takegivemodel' data-index='index2' :value="valiFormData.name" :range="range" range-key="text">
            <view class="uni-input">{{valiFormData.name ? range[valiFormData.name]: '请选择试驾城市'}}</view>
          </picker> -->
					<view class="uni-input" @click="toAreaPage">
						{{valiFormData.testCityName ? valiFormData.testCityName : '请选择试驾城市'}}
					</view>
					<image class="arrow" src="@appstatic/message/message_icon_arrow.png"></image>
				</uni-forms-item>
				<uni-forms-item label="姓名" name="testName">
					<input maxlength="30" v-model="valiFormData.testName" placeholder="请输入姓名" />
				</uni-forms-item>
				<uni-forms-item label="手机号" name="testPhone">
					<input type="number" maxlength="11" v-model="valiFormData.testPhone" placeholder="请输入手机号"
						@blur="testPhoneBlur" />
				</uni-forms-item>
				<uni-forms-item label="验证码" name="code" v-if='!!valiFormData.isCheckCode'>
					<!-- required -->
					<view class="code-box">
						<input type="number" v-model="valiFormData.code" placeholder="请输入验证码" />
						<view :class="second ? 'code-button ': 'code-button button-current'" @click="getCode">
							{{ second ? `${second}s后重获`: '获取验证码'}}</view>
					</view>
				</uni-forms-item>
				<uni-forms-item label="预约门店" name="testStoreId" v-if="storeRange.length">
					<!-- <uni-data-select v-model="valiFormData.name" :localdata="range" @change="change" placeholder="请选择预约车型"></uni-data-select> -->
					<picker @change="bindPickerStoreChange" :value="teststoreIndex" :range="storeRange"
						range-key="storeName">
						<view class="uni-input">{{valiFormData.testStoreName ? valiFormData.testStoreName: '请选择预约门店'}}
						</view>
					</picker>
					<image class="arrow" src="@appstatic/message/message_icon_arrow.png"></image>
				</uni-forms-item>
				<view class="check-box">
					<checkbox-group @change="onCheckChange">
						<label>
							<checkbox value="cb" style="transform: scale(0.64);" />
						</label>
					</checkbox-group>
					<view class="check-text">我已阅读并同意<view class="color" @click="toPrivate">《隐私政策》</view>
					</view>
				</view>
			</uni-forms>
			<button type="primary" @click="submit('valiForm')">立即预约</button>
		</view>
		<!-- 地址 -->
		<u-picker :show="showCityPicker" :columns="pickerColumns" keyName="label" confirmColor='#EA5404'
			@change="changeHandler" @cancel='pickerCancel' @confirm='pickerConfirm'></u-picker>

	</view>
</template>

<script>
	const app = getApp();
	const network = require("@manager/network-manager.js")
	import Validator from '@manager/validator.js'
	import map from "../../../utils/qqmap-wx-jssdk.min.js"
	export default {
		data() {
			return {

				isIPhoneBangs: false,
				text: '预约试驾',
				color: '#000',
				backgroundColor: 'rgba(255, 255, 255, 0)',
				swiperList: [],
				city: null,
				cityCode: null,
				testModelIndex: null,
				teststoreIndex: null,
				second: 0,
				check: false,
				valiForm: {},
				rules: {
					testModel: {
						rules: [{
							required: true,
							errorMessage: '车型不能为空'
						}]
					},
					testCity: {
						rules: [{
							required: true,
							errorMessage: '城市不能为空'
						}]
					},
					testName: {
						rules: [{
							required: true,
							errorMessage: '姓名不能为空'
						}]
					},
					testPhone: {
						rules: [{
							required: true,
							errorMessage: '手机号不能为空'
						}, {
							validateFunction: function(rule, value, data, callback) {
								if (!Validator.isMobile(value)) {
									callback('请输入正确格式的手机号')
								}
								return true
							}
						}]
					},
					code: {
						rules: [{
							required: true,
							errorMessage: '验证码不能为空'
						}]
					},
					// testStoreId: {
					// 	rules: [{
					// 		validateFunction:function(rule,value,data,callback){
					// 			console.log('rule,value,data,callback', rule,value,data,callback)
					// 			// if (value.length < 2) {
					// 			// 	callback('请至少勾选两个兴趣爱好')
					// 			// }
					// 			return true
					// 		}
					// 	}]
					// },
				},
				valiFormData: {
					testModel: null,
					testModelId: null,
					testSeriesId: null,
					testProvince: null,
					testProvinceName: null,
					testCity: null,
					testCityName: null,
					testName: app.globalData.userInfo ? app.globalData.userInfo.userName : null,
					testPhone: app.globalData.userInfo ? app.globalData.userInfo.phone : null,
					code: '',
					testSource: 2, // 1,官网 2,APP 3,小程序 4,线下导入
					testUserid: app.globalData.userInfo ? app.globalData.userInfo.id : null,
					isCheckCode: app.globalData.userInfo ? 0 : 1,
					testStoreId: null,
					testStoreName: null,
					// from: null,
					activityid: null,

				},
				range: [],
				storeRange: [],
				checkboxRange: [{
					value: 0,
					text: ""
				}],
				currentUrl: '',
				falg: false,
				/* 地址 */
				showCityPicker: false,
				pickerColumns: [
					[],
					[]
				],
			}
		},
		onPageScroll(e) {
			let opacity = Number((e.scrollTop / 340).toFixed(2))
			this.backgroundColor = `rgba(255, 255, 255, ${opacity})`
		},
		/**
		 * 用户点击右上角分享
		 */
		onShareAppMessage(res) { //发送给朋友
			return {}
		},
		onShareTimeline(res) { //分享到朋友圈
			return {}
		},
		onLoad(options) {
			this.valiFormData.testModel = options.modelName ?? null
			this.valiFormData.testModelId = options.modelId ?? null
			this.valiFormData.testRecommendId = options.testRecommendId ?? null
			this.valiFormData.isInvited = options.isInvited ?? null
			const scene = decodeURIComponent(options.scene).replace(',', '')
			this.valiFormData.activityid = scene ?? null

			wx.getSystemInfo({
				success: function(res) {
					//根据安全高度判断
					console.log("机型" + res.model);

					// var model = res.model.replace(/\s/g, "")
					// if (model == "iPhone12" || model == "iPhoneX" || model == "iPhone11" || model ==
					// 	"iPhonesx" || model == "iPhoneXR") {
					// 	this.isIPhoneBangs = true
					// } else {
					// 	this.isIPhoneBangs = false
					// }

					// this.$refs.isIPhoneBangs.showBangsHeight(this.isIPhoneBangs)

				}
			})
			this.getProvinces()
			
			//根据扫码来的storeCode带出省市
			var storeCode=options.storeCode
			// var storeCode='PF000035'
			if(storeCode && storeCode!==''){
				let url = app.globalData.config.BASE_URL + app.globalData.config.interfaces.URL_APP_GETCITYBYSTORE
				var params = {
					"storeCode": storeCode,
				};
				network.get(url, params, 'form').then(res => {
					if (res.code == 200) {
						this.valiFormData.testProvince = res.data.isProvince
						this.valiFormData.testProvinceName = res.data.provinceName
						this.valiFormData.testCity = res.data.isCity
						this.valiFormData.testCityName = res.data.cityName
						
						let uri = app.globalData.config.interfaces.URL_GETSTAGESSTORELIST
						let params = {
							"isCity": res.data.isCity,
							"dictionaryCode": 'LEVC_STORE_AREA',
							"contentCode": '002'
						}
						network.get(uri, params, 'form').then(res => {
							this.storeRange = res.data
							console.log(this.storeRange)
							var item=this.storeRange.find(x=>x.storeCode==storeCode)
							this.valiFormData.testStoreName=item.storeName
							this.valiFormData.testStoreId=item.uuid
						})
						
					}
				})
			}else{
				let _this = this
				uni.getLocation({
					type: 'wgs84',
					success: function(res) {
						var qqmapsdk = new map({
							key: 'SKABZ-LZZW5-VL7IR-IUYJA-L73D6-KMBO6' // 必填，去腾讯地图申请
						});
						qqmapsdk.reverseGeocoder({
							//Object格式
							location: {
								latitude: res.latitude,
								longitude: res.longitude
							},
							success: (res) => {
								var city = res.result.address_component.city
								_this.valiFormData.testProvince = res.result.ad_info.adcode.slice(0, 2) + '0000'
								_this.valiFormData.testProvinceName = res.result.address_component.province
								_this.valiFormData.testCity = res.result.ad_info.adcode.slice(0,4) + '00';
								// _this.valiFormData.testCityName = res.result.address_component.city
								var uri = app.globalData.config.interfaces.URL_GET_CITY_BY_PROVINCE
								var params = {"provinceCode": _this.valiFormData.testProvince};
								network.get(uri, params, 'form', {}, false).then(res2 => {
									if (res2.code == 200) {
										var cityList=res2.data.cityList
										var cityCodeSearch=_this.valiFormData.testCity
										var cityObj=cityList.find(x => x.cityCode === cityCodeSearch)
										// that.markInformation.cityName=cityObj.cityName
										_this.valiFormData.testCityName=cityObj.cityName
										_this.getStoreList(_this.valiFormData.testCity)
									} 
								}).catch(res => {
									uni.showToast({
										title: res.errMsg,
										duration: 3000,
										icon: 'none'
									})
								});
								
							},
							fail: (error) => {
								
							}
						})
					},
					fail: (err) => {
						
					},
					complete() {
				
					}
				})
			}
		},
		created(options) {
			this.getSwiperList()
			this.getCarmModelList()
			this.getStoreList()
		},
		onReady() {
			this.$refs.valiForm.setRules(this.rules)
		},
		onShow() {
			// this.valiFormData.testCity = this.cityCode
			// this.valiFormData.testCityName = this.city
			// if (!!this.cityCode) { this.getStoreList(this.cityCode) }
		},
		methods: {
			getValueByCode(list, value, valueCode, getCode) {
				let result = null
				list.forEach(item => {
					if (item[valueCode] == value) {
						result = item[getCode]
					}
				})
				return result
			},
			getSwiperList() {
				let url = app.globalData.config.BASE_URL + app.globalData.config.interfaces.URL_HOME_GET_HOME_LIST
				//轮播位置（1小程序 2APP 3官网 4H5网站）
				var isSource = 2



				//#ifdef MP-WEIXIN
				isSource = 1
				//#endif
				var params = {
					"isfrom": isSource,
					"position": 2,
					"statusFlag": 0
				};

				network.get(url, params, 'form').then(res => {
					if (res.code == 200) {
						this.swiperList = res.data
					}
				})
			},
			getCarmModelList() {
				let url = app.globalData.config.interfaces.URL_CAR_MODEL_LIST_FORAPP
				let params = {
					statusFlag: 0
				}
				network.get(url, params, 'form').then(res => {
					this.range = res.data
					if (this.valiFormData.testModelId) {
						this.valiFormData.testSeriesId = this.getValueByCode(res.data, this.valiFormData
							.testModelId, 'uuid', 'seriesId')
						this.currentUrl = this.getValueByCode(this.range, this.valiFormData.testModelId, 'uuid',
							'imageTestCover')
					}
				})
			},
			async getStoreList(city) {
				if (!city) return
				let url = app.globalData.config.interfaces.URL_GETSTAGESSTORELIST
				let params = {
					"isCity": city,
					"dictionaryCode": 'LEVC_STORE_AREA',
					"contentCode": '002'
				}
				await network.get(url, params, 'form').then(res => {
					this.storeRange = res.data
				})
			},
			onCheckChange(e) {
				this.check = e.detail.value.length > 0
			},
			bindPickerChange(data) {
				this.testModelIndex = data.detail.value
				this.valiFormData.testModel = this.range[data.detail.value]['modelName']
				this.valiFormData.testModelId = this.getValueByCode(this.range, this.range[data.detail.value]['modelName'],
					'modelName', 'uuid')
				this.valiFormData.testSeriesId = this.getValueByCode(this.range, this.valiFormData.testModelId, 'uuid',
					'seriesId')
				this.currentUrl = this.getValueByCode(this.range, this.valiFormData.testModelId, 'uuid', 'imageTestCover')
				console.log('this.valiFormData', this.valiFormData)
			},
			bindPickerStoreChange(data) {
				this.teststoreIndex = data.detail.value
				this.valiFormData.testStoreId = this.storeRange[data.detail.value]['uuid']
				this.valiFormData.testStoreName = this.storeRange[data.detail.value]['storeName']
			},
			testPhoneBlur(e) {
				this.valiFormData.isCheckCode = (app.globalData.userInfo.phone == e.detail.value) ? 0 : 1
				this.valiFormData.code = ''
			},
			getCode() {
				var that = this
				if (this.falg) {
					return
				}
				if (!this.valiFormData.testPhone) {
					uni.showToast({
						title: '请输入手机号',
						duration: 2000,
						icon: 'none'
					})
					return
				}
				if (!Validator.isMobile(this.valiFormData.testPhone)) {
					uni.showToast({
						title: '请输入正确格式的手机号',
						duration: 2000,
						icon: 'none'
					})
					return
				}
				if (this.second !== 0) return
				let url = app.globalData.config.interfaces.URL_TESTDRIVER_CODE
				let params = {
					phone: this.valiFormData.testPhone
				}
				this.falg = true
				network.post(url, params, 'form').then(res => {
					if (res.code == 200) {
						uni.showToast({
							title: '获取成功',
							duration: 2000,
							icon: 'none'
						})
						this.getCodeSecond()
					} else {
						uni.showToast({
							title: res.message,
							duration: 2000,
							icon: 'none'
						})
					}
					that.falg = false
				})
			},
			getCodeSecond() {
				if (this.second !== 0) return
				this.second = 59
				let second = this.second
				let timer = setInterval(() => {
					if (second == 0) {
						clearInterval(timer)
						return
					}
					second = second - 1
					this.second = second
				}, 1000)
			},
			/* 省市 */
			//获取省
			async getProvinces() {
				var url = app.globalData.config.interfaces.URL_GET_PROVINCE
				var params = {
					// "loginId": app.getUserId()
				}
				await network.get(url, params, 'form').then(res => {
					if (res.code == 200) {
						let arr = []
						res.data.ProvinceList.map(item => {
							item.label = item.provinceName, item.code = item.provinceCode, arr.push(
								item)
						})
						this.pickerColumns.splice(0, 1, arr)
						this.getCitys(this.pickerColumns[0][0]['provinceCode'])
					} else {
						uni.showToast({
							title: res.message,
							duration: 2000,
							icon: 'none'
						})
					}
				}).catch(res => {

				});
			},

			//获取市
			async getCitys(code) {
				var url = app.globalData.config.interfaces.URL_GET_CITY_BY_PROVINCE
				var params = {
					// "loginId": app.getUserId(),
					"provinceCode": code
				}
				await network.get(url, params, 'form').then(res => {
					if (res.code == 200) {
						let arr = []
						res.data.cityList.map(item => {
							item.label = item.cityName, item.code = item.cityCode, arr.push(item)
						})
						this.pickerColumns.splice(1, 1, arr)
					} else {
						uni.showToast({
							title: res.message,
							duration: 2000,
							icon: 'none'
						})
					}
				}).catch(res => {

				});
			},
			changeHandler(e) {
				const {
					columnIndex,
					index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.uPicker
				} = e
				if (columnIndex === 0) {
					this.getCitys(this.pickerColumns[0][index]['provinceCode'])
				}
				// picker.setIndexs([1, 0])
			},

			pickerCancel() {
				this.showCityPicker = false
			},

			pickerConfirm(e) {
				this.valiFormData.testProvince = e.value[0].code
				this.valiFormData.testProvinceName = e.value[0].label
				this.valiFormData.testCity = e.value[1].code
				this.valiFormData.testCityName = e.value[1].label
				this.pickerCancel()
				this.getStoreList(this.valiFormData.testCity)
				this.valiFormData.testStoreId = null
				this.valiFormData.testStoreName = null
			},

			async submit() {
				await this.$refs.valiForm.validate()
				if (this.storeRange.length && !this.valiFormData.testStoreId) {
					uni.showToast({
						title: '请选择预约门店',
						duration: 2000,
						icon: 'none'
					})
					return
				}
				if (!this.check) {
					uni.showToast({
						title: '请选择隐私条款',
						duration: 2000,
						icon: 'none'
					})
					return
				}
				let url = app.globalData.config.interfaces.URL_TESTDRIVER_CREATE
				network.post(url, this.valiFormData, 'json', null, true).then(res => {
					if (res.code == 200) {
						this.toCompletePage()
					} else {
						setTimeout(() => {
							wx.showToast({
								title: res.message,
								mask: true,
								icon: 'none',
								duration: 2000
							});
						}, 500);
					}
				})
			},
			toAreaPage() {
				this.showCityPicker = true
				// uni.navigateTo({
				// 	url: "/module_my/pages/myArea/myArea",
				// });
			},
			toCompletePage() {
				uni.redirectTo({
					url: `/module_car/pages/testDrive/complete?url=${this.currentUrl}`,
				});
			},
			toPrivate() {
				uni.navigateTo({
					url: "/pages/user/private",
				});
			},
		}
	}
</script>

<style lang="less">
	page {
		/* background: #E5E5E5; */
		margin-bottom: 16px;
	}

	.title-container .title {
		font-size: 16px;
	}

	.uni-margin-wrap {
		width: 100vw;
		height: 100vw;
		overflow: hidden;
	}

	uni-swiper {
		width: 100%;
		height: 100%;
	}

	.uni-margin-wrap .swiper-item .item {
		width: 100%;
	}

	.uni-margin-wrap .swiper-item .item image {
		width: 100%;
	}

	/deep/ uni-swiper .uni-swiper-dots-horizontal {
		bottom: 95px;
	}

	/deep/ uni-swiper .uni-swiper-dot {
		width: 10px;
		height: 2px;
		border-radius: 0;
	}

	/deep/ uni-swiper .uni-swiper-dot-active {
		width: 20px;
		height: 2px;
		border-radius: 0;
	}

	/deep/ uni-swiper .uni-swiper-dots-horizontal .uni-swiper-dot {
		margin-right: 4px;
	}




	.example {
		position: absolute;
		width: calc(100vw - 32px);
		top: calc(100vw - 92px);
		box-sizing: border-box;
		padding: 4px 20px 16px;
		margin: 16px;
		background: #FFFFFF;
		box-shadow: 0px 0px 19px rgba(0, 0, 0, 0.08);
		border-radius: 4px;
	}

	/deep/ .uni-stat__select {
		padding: 0;
	}

	/deep/ .uni-forms-item__inner {
		padding-bottom: 0;
		border-bottom: 1px solid #F0F0F0;
	}

	/deep/ .uni-forms-item__label .label-text {
		font-size: 12px;
		color: #828282;
	}

	/deep/ .is-input-border {
		border: none;
		height: 50px;
	}

	/deep/ .uni-input-input {
		font-size: 16px;
		color: #333333;
	}

	/deep/ .uni-forms-item__content {
		font-size: 16px;
		color: #333333;
		line-height: 50px;
		position: relative;
	}

	/deep/ .uni-easyinput__content-input {
		padding: 0 !important;
	}

	/deep/ .uni-input-placeholder {
		font-weight: 400;
		font-size: 16px;
		color: #333333;
	}

	.check-box {
		display: flex;
		padding: 18px 0 13px;
		text-align: center;
		justify-content: center;
		align-items: center;
	}

	/deep/ .check-box .uni-data-checklist {
		width: 20px;
		overflow: hidden;
		flex: none;
	}

	.check-box .check-text {
		font-size: 12px;
		line-height: 12px;
		color: #ADB0AE;
	}

	.check-box .check-text .color {
		display: inline-block;
		color: #EA5404;
	}

	// /deep/uni-checkbox {
	// 	width: 10px;
	// 	height: 10px;
	// }

	// /deep/ .uni-data-checklist .checklist-group .checklist-box .checkbox__inner {
	// 	width: 10px;
	// 	height: 10px;
	// }

	/deep/ .uni-data-checklist .checklist-group .checklist-box .checkbox__inner .checkbox__inner-icon {
		top: 0;
		left: 4px;
	}

	/deep/ .uni-data-checklist .checklist-group .checklist-box.is--default.is-checked .checkbox__inner {
		background-color: #EA5404 !important;
		border-color: #EA5404 !important;
	}

	/deep/uni-checkbox:not([disabled]) .uni-checkbox-input:hover {
		border-color: #EA5404;
	}

	// /deep/uni-checkbox .uni-checkbox-input {
	// 	width: 10px;
	// 	height: 10px;
	// }

	// /deep/uni-checkbox .uni-checkbox-input.uni-checkbox-input-checked:before {
	// 	font-size: 10px;
	// }

	/deep/uni-checkbox .uni-checkbox-input {
		border-color: #EA5404;
	}

	/deep/uni-checkbox .uni-checkbox-input.uni-checkbox-input-checked {
		border: 1px solid #EA5404;
	}

	button {
		background-color: #EA5404 !important;
		font-weight: 400;
		font-size: 16px;
		color: #FFFFFF;
		line-height: 40px;
	}

	/deep/ .button-hover {
		background-color: #EA5404 !important;
		border-color: #EA5404 !important;
	}

	/deep/ .uni-picker-container .uni-picker-action.uni-picker-action-confirm {
		color: #EA5404 !important;
	}

	.code-box {
		display: flex;
	}

	.code-box uni-input {
		flex: 1;
	}

	.code-box .code-button {
		background: #F1F2F3;
		border-radius: 2px;
		font-size: 12px !important;
		line-height: 30px !important;
		height: 30px !important;
		padding: 0 20px;
		color: #BCBDBE;
		margin-top: 10px;
	}

	.code-box .button-current {
		background: #EA5404;
		color: #fff;
	}

	uni-input {
		height: 50px;
	}

	.arrow {
		position: absolute;
		width: 12px;
		height: 16px;
		right: 2px;
		bottom: 11px;
		transform: rotate(90deg);
	}



	/* wx */

	wx-swiper .wx-swiper-dots-horizontal {
		bottom: 120px;
	}

	wx-swiper .wx-swiper-dot {
		width: 10px;
		height: 2px;
		border-radius: 0;
	}

	wx-swiper .wx-swiper-dot-active {
		width: 20px;
		height: 2px;
		border-radius: 0;
	}

	wx-swiper .wx-swiper-dots-horizontal .wx-swiper-dot {
		margin-right: 4px;
	}
</style>
